
import 'dart:async';
import 'dart:convert';
import 'package:draggable_float_widget/draggable_float_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:single/event/user_id_event.dart';

import '../entity/book_entity.dart';
import '../entity/current_task_entity.dart';
import '../entity/reader_entity.dart';
import '../event/wrong_way_event.dart';
import '../event/auth_face_success_event.dart';
import '../event/check_status_event.dart';
import '../event/door_status_event.dart';
import '../event/index_refresh_event.dart';
import '../event/light_status_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/toast_util.dart';
import '../widget/auth_dialog.dart';
import '../widget/dialog_widget.dart';
import 'book_detail_page.dart';
import 'borrow_result_page.dart';
import 'mine_page.dart';

class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {

  late StreamController<OperateEvent> eventStreamController;

  StreamSubscription? userSubscription;
  StreamSubscription? doorSubscription;
  StreamSubscription? lightSubscription;
  StreamSubscription? refreshSubscription;
  StreamSubscription? wrongWaySubscription;
  StreamSubscription? doorErrorSubscription;
  StreamSubscription? authFaceSuccessSubscription;


  final RxList<BookEntity> list = RxList();


  @override
  initState()  {
    super.initState();

    eventStreamController = StreamController.broadcast();

    try{
      hfSerialPortHelper.sendData(checkStatus());
    }catch(e){
      print(e);
    }


    doorSubscription = eventFactory.on<DoorStatusEvent>().listen((event) {
      if(Get.isDialogOpen != null && Get.isDialogOpen!){
        Get.back();
      }

      if(event.isOpen){
        hfSerialPortHelper.sendData(openLight());
        if(currentTask.uid!=null && currentTask.readerEntity != null){
          DialogWidget().doorOpenDialog(currentTask.readerEntity!);
        }else{
          if(Get.rawRoute != null && Get.rawRoute!.isFirst){
            DialogWidget().adminDoorOpenDialog();
          }else{

          }

        }
      }else{
        hfSerialPortHelper.sendData(closeLight());
        if(Get.rawRoute != null && Get.rawRoute!.isFirst){
          if( currentTask.uid != null){
            Get.to(() => const BorrowResult());
          }
        }
      }
    });
    doorSubscription = eventFactory.on<UserIdEvent>().listen((event) {
      currentTask.uid = event.uid;

      _goAfterAuth();
    });

    wrongWaySubscription = eventFactory.on<WrongWayEvent>().listen((event) {
      hfSerialPortHelper.sendData(checkStatus());
    });

    doorErrorSubscription = eventFactory.on<CheckStatusEvent>().listen((event) {
        if(event.door){
          Future.delayed(const Duration(seconds: 1),(){
            DialogWidget().warnOpenDialog();
          });
        }
        if(event.light1){
          hfSerialPortHelper.sendData(closeLight());
        }
    });

    lightSubscription = eventFactory.on<LightStatusEvent>().listen((event) {


    });
    refreshSubscription = eventFactory.on<IndexRefreshEvent>().listen((event) {
      list.clear();
      _showList();
      // list.addAll(bookQueryAll().where((element) => element.statue == 0).toList()..sort((a, b) => a.recommend!.compareTo(b.recommend!)));

    });

    authFaceSuccessSubscription = eventFactory.on<AuthFaceSuccessEvent>().listen((event) {
      _goAfterAuth();
    });


    // list.addAll(bookQueryAll().where((element) => element.statue == 0).toList()..sort((a, b) => a.recommend!.compareTo(b.recommend!)));
    _showList();
    _lockScreen();
  }

  _showList(){
    var allList = bookQueryAll();
    if(allList.isNotEmpty){
      list.addAll(allList.where((element) => element.statue == 0).toList()..sort((a, b) => a.recommend!.compareTo(b.recommend!)));
    }
  }

  _lockScreen() async {
    await const MethodChannel('toAndroid').invokeMethod('hideBar');
  }

  @override
  void dispose() {
    eventStreamController.close();
    userSubscription?.cancel();
    userSubscription= null;
    authFaceSuccessSubscription?.cancel();
    authFaceSuccessSubscription= null;
    doorSubscription?.cancel();
    doorSubscription= null;
    lightSubscription?.cancel();
    lightSubscription= null;
    refreshSubscription?.cancel();
    refreshSubscription= null;
    wrongWaySubscription?.cancel();
    wrongWaySubscription= null;
    doorErrorSubscription?.cancel();
    doorErrorSubscription= null;
    hfSerialPortHelper.close();
    idSerialPortHelper?.close();
    idSerialPortHelper = null;
    books.close();
    super.dispose();
  }

  _goAfterAuth() async {
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    var data = await findReader(currentTask.uid);
    if(data == null){
      currentTask.uid = null;
      toastWarn('读者号不存在');
      tts.speak("读者号不存在");
      return;
    }
    if(!data.validReader!){
      currentTask.uid = null;
      toastWarn('读者卡未注册');
      tts.speak("读者卡未注册");
      return;
    }
    idSerialPortHelper?.close();
    idSerialPortHelper = null;
    currentTask.readerEntity = data;
    //个人中心
    if(currentTask.task == Task.toMine){
      currentTask.uName = data.name;
      Get.to(()=> const Mine(),arguments: data);
      return;
    }

    if(currentTask.task == Task.borrow){
      _reqReaderInfo(data);
    }

  }

  _reqReaderInfo(ReaderEntity? data) async {
    if(data != null){
      // if(currentTask.needCheckCount){
      //   if(data.currentBorrowCount! >= data.limitCount!){
      //     toastError("已至最大借书数量，请先还书");
      //     tts.speak("已至最大借书数量，请先还书");
      //     Future.delayed(const Duration(seconds: 2),(){
      //       currentTask.clear();
      //     });
      //     timer.cancel();
      //     Get.until((route) => route.isFirst);
      //     return;
      //   }
      //   if(data.currentBorrowList !=null ){
      //     for (var element in data.currentBorrowList!) {
      //       if(element.overdue!){
      //         toastError("借阅已超时，请先还书");
      //         tts.speak("借阅已超时，请先还书");
      //         Future.delayed(const Duration(seconds: 2),(){
      //           currentTask.clear();
      //         });
      //         timer.cancel();
      //         Get.until((route) => route.isFirst);
      //         return;
      //       }
      //     }
      //   }
      // }
      currentTask.offset = data.limitCount!-data.currentBorrowCount!;
      hfSerialPortHelper.sendData(openDoor());
    }else{
      timer.cancel();
      toastWarn("用户不存在");
      Get.until((route) => route.isFirst);
    }

  }

  _subTitle(String? title){
    if(title != null && title.length >8){
      return title.substring(0,8);
    }
    return title;
  }

  _itemBuilder(index){
    var item = list[index];
    return InkWell(
      onTap: (){
        Get.to(() => const BookDetail(),arguments: item);
      },
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [

          item.cover!= ''?Image.memory(base64Decode(item.cover??''),
            width: 83.w,
            height: 105.h,
            fit: BoxFit.cover,
          ): Image.asset("assets/images/default.jpg",height: 105.h, width: 83.w, fit: BoxFit.cover,),
          Visibility(
            visible: item.recommend == 1,
            child: Positioned(
                top: 10.h,
                right: 8.w,
                child: Image.asset("assets/images/recommend_icon.png",width: 20.w,fit: BoxFit.fitWidth,)
            ),
          ),

          Positioned(
            bottom: 0.h,
            child: Text('《${_subTitle(item.mainTitle)}》',overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 10.sp),)
          ),
        ],
      ),
    );
  }

  _searchBarWidget(){
    return Container(
        decoration:BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(16.r)),
        ),
        padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
        margin:  EdgeInsets.only(left: 20.w, right: 20.w, bottom: 15.h,top: 15.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset("assets/images/search_icon.png",width:18.w,height:18.w),
            SizedBox(width: 4.w,),
            SizedBox(
              width: 320.w,
              child: TextField(
                  minLines: 1,
                  textInputAction: TextInputAction.search,
                  onChanged: (input){
                    // _keyWord = input;
                    list.clear();
                    if(input.isNotEmpty){
                      list.addAll(bookQueryByKey(input).where((element) => element.statue == 0).toList()..sort((a, b) => a.recommend!.compareTo(b.recommend!)));
                    }else{
                      list.addAll(bookQueryAll().where((element) => element.statue == 0).toList()..sort((a, b) => a.recommend!.compareTo(b.recommend!)));

                    }
                  },
                  decoration: const InputDecoration(
                    isCollapsed: true,
                    border: InputBorder.none,
                    hintText: "按 书名 作者 索书号等关键字 检索",
                  ),

                  style: TextStyle(color: Colors.black,fontSize: 12.sp)
              ),

            ),
          ],
        )
    );
  }


  Widget get defaultList => Container(
    width: double.infinity,
    margin: EdgeInsets.only(top: 200.h,left: 12.w,right: 12.w),
    decoration: const BoxDecoration(
        color: Color.fromRGBO(242,254, 255, 1)
    ),
    child: NotificationListener(
      onNotification: (notification) {
        if (notification is ScrollStartNotification) {
          eventStreamController.add(OperateEvent.OPERATE_HIDE);
        } else if (notification is ScrollEndNotification) {
          eventStreamController.add(OperateEvent.OPERATE_SHOW);
        }
        return true;
      },
      child: Obx(() => list.isNotEmpty?GridView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: list.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:0.65,  crossAxisSpacing: 8.w, mainAxisSpacing: 5.h),
      ): Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 50.h,),
          Text('未搜索到图书，可尝试搜索其他书籍',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12.sp,color: const Color.fromRGBO(29, 125, 168, 1)),),
          Image.asset('assets/images/index_empty.png',width: 300.w,fit: BoxFit.fitWidth,)
        ],
      ))
    ),
  );

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        body: Stack(
          children: [
            Image.asset('assets/images/index_logo.png',fit: BoxFit.cover,width: 400.w,height: 200.h,),
            Positioned(top:150.h,child: _searchBarWidget(),),
            defaultList,
            InkWell(
              onTap: (){
                DialogWidget().adminLoginDialog();
              },
              child: SizedBox(width: 100.w,height: 100.w,),
            ),

            DraggableFloatWidget(
              eventStreamController: eventStreamController,
              config: const DraggableFloatWidgetBaseConfig(
                isFullScreen: false,
                initPositionYInTop: false,
                initPositionXInLeft: false,
                initPositionYMarginBorder: 30,
                borderBottom: 20 + defaultBorderWidth,
              ),
              onTap: () {
                currentTask.task = Task.toMine;
                AuthDialog().authTypeDialog();
              },
              width: 100,
              height: 100,
              child: Image.asset('assets/images/mine.png'),
            ),
            DraggableFloatWidget(
              eventStreamController: eventStreamController,
              config: const DraggableFloatWidgetBaseConfig(
                isFullScreen: false,
                initPositionYInTop: false,
                initPositionXInLeft: false,
                initPositionYMarginBorder: 30,
                borderBottom:120 + defaultBorderWidth,
              ),
              onTap: () {
                currentTask.task = Task.borrow;
                AuthDialog().authTypeDialog();
              },
              width: 100,
              height: 100,
              child: Image.asset('assets/images/open.png'),
            )

          ],
        ),
      ),
    );
  }
}